package com.corechina.apex_osswords.common.config.oauth2;


import com.corechina.apex_osswords.common.IPUtils;
import com.corechina.apex_osswords.common.Response;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * oauth2过滤器
 */

@Slf4j
public class OAuth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) request);

        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return new OAuth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;
        log.info("ip: " + IPUtils.getIpAddr(req) + " , 请求: " + req.getServletPath());
        if (req.getMethod().equals(RequestMethod.OPTIONS.toString()) || req.getMethod() == RequestMethod.OPTIONS.toString()) {
            return true;
        }
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        this.setCors(httpResponse);
        if (org.apache.commons.lang.StringUtils.isEmpty(token)) {
            Response r = Response.error(HttpStatus.UNAUTHORIZED.value(), "invalid token");
            String json = new Gson().toJson(r);
            httpResponse.getWriter().print(json);
            log.error("{} , invalid token", HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Response r = Response.error(HttpStatus.UNAUTHORIZED.value(), throwable.getMessage());
            String json = new Gson().toJson(r);
            httpResponse.getWriter().print(json);
        } catch (Exception e1) {
            log.error("onLoginFailure error!", e1);
        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("Authorization");
        //如果header中不存在token，则从参数中获取token
        if (null == token || StringUtils.isEmpty(token)) {
            token = httpRequest.getParameter("Authorization");
        }
        if (!StringUtils.isEmpty(token)) {
            return token.trim();
        }
        return null;
    }

    private void setCors(HttpServletResponse httpResponse) {
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    }

}
